<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-input class="cd-mb8" v-model="filterText" placeholder="请输入" clearable size="small"
            prefix-icon="el-icon-search" />
          <el-tree class="input-tree" :data="treeList" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
            node-key="id" highlight-current @node-click="handleNodeClick">
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <div class="header-title">
            <span>第</span>
            <el-select class="cd-ml8 cd-mr8" v-model="queryParams.measureQhId" placeholder="" size="mini"
              style="width: 60px" @change="qsChange">
              <el-option v-for="item in qsOptions" :key="item.measureQhId" :label="item.qh"
                :value="item.measureQhId"></el-option>
            </el-select>
            <span>期计量列表</span>
            <span v-if="qsInfo && qsInfo.beginDate" class="cd-ml8 cd-mr8"> ( {{ parseTime(qsInfo.beginDate,
              "{y}-{m}-{d}") }} - {{ parseTime(qsInfo.endDate, "{y}-{m}-{d}") }}) </span>
          </div>
          <!-- 新增按钮获取期数日期范围内的所有签收材料（去重数量合并）
          计量数量计量金额默认签收材料数量总金额
          报表计算时使用计量数量、计量金额 -->
          <el-row v-if="treeInfo && treeInfo.type == 'supplier'" :gutter="10"
            class="mb8 cd-pr8 top-right-btn small-line-height">
            <el-button v-if="canUpdate" type="success" plain size="mini" :loading="buttonLoading" @click="submitForm"
              v-hasPermi="['ma:materialMeasureSingle:edit']" :disabled="!canOperation()">保存</el-button>
            <el-button v-else type="primary" plain size="mini" @click="onUpdate"
              v-hasPermi="['ma:materialMeasureSingle:edit']" :disabled="!canOperation()">编辑</el-button>
          </el-row>
          <el-form ref="form" :model="form" :rules="rules" label-width="0px">
            <el-table border stripe v-loading="loading" :data="form.dataList" :summary-method="getSummaries"
              show-summary>
              <el-table-column label="材料编号" align="center" prop="manifestCode" min-width="120" show-overflow-tooltip />
              <el-table-column label="材料名称" align="center" prop="manifestName" min-width="120" show-overflow-tooltip />
              <el-table-column label="型号" align="center" prop="model" min-width="100" show-overflow-tooltip />
              <el-table-column label="规格" align="center" prop="specification" min-width="100" show-overflow-tooltip />
              <el-table-column label="单位" align="center" prop="unit" min-width="80" show-overflow-tooltip />
              <el-table-column label="数量" header-align="center" align="right" prop="number" min-width="100"
                show-overflow-tooltip> </el-table-column>
              <!-- <el-table-column label="市场单价" align="center" prop="marketPrice" min-width="120" show-overflow-tooltip />
            <el-table-column label="调整额" align="center" prop="adjustments" min-width="120" show-overflow-tooltip /> -->
              <el-table-column label="结算单价" header-align="center" align="right" prop="settlementPrice" min-width="100"
                show-overflow-tooltip />
              <el-table-column label="金额" header-align="center" align="right" prop="total" min-width="120"
                show-overflow-tooltip />
              <el-table-column label="交接验收单据号" align="center" prop="acceptanceCode" min-width="120"
                show-overflow-tooltip />
              <el-table-column label="计量数量" header-align="center" align="right" prop="meNum" min-width="120">
                <!--  v-if="canUpdate && scope.row.settlementPrice" -->
                <template slot-scope="scope">
                  <el-form-item v-if="canUpdate && scope.row.settlementPrice"
                    :prop="'dataList.' + scope.$index + '.meNum'" :rules="rules.meNum">
                    <el-input-number size="mini" v-model="scope.row.meNum" placeholder="" :precision="2"
                      :controls="false" style="width: 100%" @change="meNumChange(scope.row)"></el-input-number>
                  </el-form-item>
                  <span v-else>{{ scope.row.meNum || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="计量金额" header-align="center" align="right" prop="meTotal" min-width="120"
                show-overflow-tooltip />
              <el-table-column label="截止上期未计量数量" header-align="center" align="right" prop="preUnmeNum" min-width="140"
                show-overflow-tooltip />
            </el-table>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { allListMaterialMeasureQh } from "@/api/ma/materialMeasureQh";
import { progressDetails, updateMaterialMeasureSingle } from "@/api/ma/materialMeasureSingle";
import { querySupplierTreeList } from "@/api/base/bsBd";
import { getReportFormPaymentByQhId } from "@/api/ma/paymentReportForm";

import { mapGetters } from "vuex";
import decimal from "@/utils/big-decimal";

export default {
  name: "MaterialMeasureSingle",
  data () {
    // 计量数量
    const meNumValidator = (rule, value, callback) => {
      if (!value) {
        return callback();
      }
      // 计算计量数量不可超过总数量
      // 拆分获取index
      const field = rule.field;
      const arr = field.split(".");
      if (arr.length == 3) {
        const index = arr[1];
        // 总剩余数量
        const totalNumber = this.form.dataList[index].totalNumber;
        if (Number(value) > Number(totalNumber)) {
          // 数量归零
          this.form.dataList[index].meNum = 0;
          this.meNumChange(this.form.dataList[index]);
          return callback(new Error("计量已超量!"));
        }
      }
      callback();
    };
    return {
      isHide: false,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      filterText: undefined,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      qsOptions: [],
      qsInfo: {},
      // 材料计量单表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        measureQhId: undefined,
        zdId: undefined,
        gysId: undefined
      },
      projectId: undefined,
      workflowsStateus: "", // 报表状态
      canUpdate: false,
      // 表单参数
      form: {
        dataList: []
      },
      // 表单校验
      rules: {
        meNum: [{ validator: meNumValidator, trigger: "blur" }]
      }
    };
  },
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    },
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.getBdTree();
    },
    getBdTree () {
      querySupplierTreeList({ projectId: this.projectId }).then((response) => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0) {
            // this.$refs.tree.setCurrentKey(this.treeList[0].id);
            // this.handleNodeClick(this.treeList[0]);
          } else {
            this.treeInfo = {};
            this.queryParams.bdId = null;
            this.queryParams.zdId = null;
            this.dataList = [];
            this.total = 0;
          }
        });
      });
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick (data) {
      this.treeInfo = data;
      if (data.type == "supplier") {
        this.queryParams.zdId = data.parentId; // 站点ID
        this.queryParams.gysId = data.id; // 供应商ID
        this.getQsList();
      } else {
        // this.$message.warning("请选择供应商！");
      }
    },
    getQsList () {
      const query = {
        gysId: this.queryParams.gysId
      };
      allListMaterialMeasureQh(query).then((res) => {
        this.qsOptions = res.data;
        if (this.qsOptions.length > 0) {
          // 默认期数
          let qsInfo = this.qsOptions.find((item) => item.currentQhFlag == 1);
          if (!qsInfo) {
            qsInfo = this.qsOptions[this.qsOptions.length - 1];
          }
          this.qsInfo = qsInfo;
          this.queryParams.measureQhId = qsInfo.measureQhId;
          // this.queryParams.qs = qsInfo.qs;
          this.qsChange();
        } else {
          this.queryParams.measureQhId = null;
          this.workflowsStateus = "";
          this.form.dataList = [];
        }
      });
    },
    qsChange () {
      this.qsInfo = this.qsOptions.find((item) => item.measureQhId == this.queryParams.measureQhId);
      this.getList();
      // 获取审批状态
      this.getWorkflowsStateus();
    },
    // 获取审批状态
    getWorkflowsStateus () {
      const query = {
        measureQhId: this.queryParams.measureQhId,
        gysId: this.qsInfo.gysId
      };
      getReportFormPaymentByQhId(query).then((response) => {
        const { workflowsStateus } = response.data;
        this.workflowsStateus = workflowsStateus || "00";
      });
    },
    /** 查询材料计量单列表 */
    getList () {
      this.loading = true;
      const queryParams = {
        gysId: this.queryParams.gysId,
        measureQhId: this.qsInfo.measureQhId,
        qh: this.qsInfo.qh,
        beginDate: this.qsInfo.beginDate,
        endDate: this.qsInfo.endDate
      };
      progressDetails(queryParams).then((response) => {
        this.form.dataList = response.data || [];
        // 计算可计量总数量
        if (this.form.dataList.length > 0) {
          this.form.dataList.forEach((item) => {
            item["totalNumber"] = decimal.add(item.number, item.preUnmeNum || 0, 3);
          });
        }
        this.loading = false;
        this.canUpdate = false;
      });
    },
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 6 || index === 9) {
          const values = data.map((item) => Number(item[column.property]));
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return decimal.add(prev, curr);
              } else {
                return decimal.round(prev);
              }
            }, 0);
            sums[index] += "";
          } else {
            sums[index] = "";
          }
        }
      });

      return sums;
    },
    meNumChange (row) {
      // 计算总金额
      row.meTotal = decimal.multiply(row.settlementPrice, row.meNum);
      // // 计算剩余数量
      // row.remainingQuantity = decimal.subtract(row.totalNumber, row.meNum);
      return row;
    },
    // 是否可操作
    canOperation () {
      return this.workflowsStateus == "00" || this.workflowsStateus == "33";
    },
    /** 编辑按钮操作 */
    onUpdate () {
      this.canUpdate = true;
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          const info = {
            updateList: this.form.dataList
          };
          updateMaterialMeasureSingle(info)
            .then((response) => {
              this.$modal.msgSuccess("保存成功");
              this.canUpdate = false;
              this.getList();
            })
            .finally(() => {
              this.buttonLoading = false;
            });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "ma/materialMeasureSingle/export",
        {
          ...this.queryParams
        },
        `materialMeasureSingle_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.header-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
  font-size: 20px;
  font-weight: 700;
}
</style>
